package com.mofeng.myshop.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mofeng.myshop.domain.dto.OrderFromDto;
import com.mofeng.myshop.domain.dto.search.OrderFromSearchDto;
import com.mofeng.myshop.domain.po.*;
import com.mofeng.myshop.domain.vo.OrderFromVo;
import com.mofeng.myshop.domain.vo.base.PageMp;
import com.mofeng.myshop.domain.vo.user.UserVo;
import com.mofeng.myshop.mapper.*;
import com.mofeng.myshop.service.IOrderFromService;
import com.mofeng.myshop.service.ISettingService;
import com.mofeng.myshop.service.PermissionService;
import com.mofeng.myshop.until.*;
import com.mofeng.myshop.until.rcon.Rcon;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
import java.util.regex.*;

/**
 * <p>
 * 订单 服务实现类
 * </p>
 *
 * @author MoFeng
 * @since 2024-04-14
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class OrderFromServiceImpl implements IOrderFromService {

    private final CommodityMapper commodityMapper;

    private final CommodityCategoryMapper commodityCategoryMapper;

    private final UserBaseMapper userBaseMapper;

    private final UserInfoMapper userInfoMapper;

    private final AddressMapMapper addressMapper;

    private final OrderFromMapper orderFromMapper;

    private final PermissionService permissionService;

    private final ISettingService settingService;

    /**
     * 添加到购物车
     *
     * @param orderFromDto 订单详情
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R addToShopping(OrderFromDto orderFromDto) {
        OrderFrom orderFrom = orderFromDto.toEntity();
        checkAndCalcMsg(orderFrom, false);
        orderFromMapper.insert(orderFrom);

        return R.SUCCESS("已添加到购物车", new OrderFromVo(orderFrom));
    }

    /**
     * 修改购物车物品
     *
     * @param orderFromDto 订单详情
     */
    @Override
    public R updateShopping(OrderFromDto orderFromDto) {
        OrderFrom orderFrom = orderFromDto.toEntity();
        checkAndCalcMsg(orderFrom, false);
        orderFromMapper.updateById(orderFrom);
        return R.SUCCESS("物品修改成功", new OrderFromVo(orderFrom));
    }

    /**
     * 检查信息并且计算价格
     */
    private void checkAndCalcMsg(OrderFrom orderFrom, boolean checkAddress) {
        AddressMap address = null;
        if (checkAddress) {
            Long addressId = orderFrom.getAddressId();
            if (addressId == null) {
                throw new RuntimeException("请选择地图服务器");
            }

            address = addressMapper.selectById(addressId);
            if (address == null) {
                throw new RuntimeException("找不到地图服务器");
            }
        }
        orderFrom.setAddressMap(address);
        Long commodityId = orderFrom.getCommodityId();
        if (commodityId == null) {
            throw new RuntimeException("请选择商品");
        }
        Commodity commodity = commodityMapper.selectById(commodityId);
        if (commodity == null) {
            throw new RuntimeException("找不到商品");
        }
        orderFrom.setCommodity(commodity);

        CommodityCategory commodityCategory = commodityCategoryMapper.selectById(commodity.getCommodityCategoryId());
        orderFrom.setCommodityCategory(commodityCategory);

        UserVo userVo = LoginUserThreadLocalUtil.get();
        if (userVo == null) {
            throw new RuntimeException("用户未登录");
        }

        Long buyUserId = MyUtil.NumberUtil.asLong(userVo.getId());
        UserBase buyUserFromDb = userBaseMapper.selectById(buyUserId);
        if (buyUserFromDb == null) {
            throw new RuntimeException("找不到登录用户");
        }
        orderFrom.setBuyUser(buyUserFromDb);
        orderFrom.setBuyUserId(buyUserFromDb.getId());

        //计算价格

        //蓝图价格
        String isBluePic = orderFrom.getIsBluePic();
        int bluePicMoney = Constants.Order.IS_BLUE_PIC.equals(isBluePic) ? 2 : 1;

        if (orderFrom.getCount() == null) {
            orderFrom.setCount(1);
        }
        Integer count = orderFrom.getCount();
        //等级价格
        Integer level = orderFrom.getLevel();
        Double levelUp = commodity.getLevelUp();
        levelUp = levelUp != null && levelUp > 0 ? levelUp : 0;
        Integer levelTop = commodity.getLevelTop();
        if (levelTop != null && levelTop > 0 && (level >= levelTop)) {
            level = levelTop - 1;
            orderFrom.setLevel(level);
        }

        Double levelMoney = (level - 1) * levelUp;

        //品质价格
        Integer multiplier = orderFrom.getMultiplier();
        Double multiplierUp = commodity.getMultiplierUp();
        multiplierUp = multiplierUp != null && multiplierUp > 0 ? multiplierUp : 0;
        Double multiplierMoney = (multiplier) * multiplierUp;
        Double price = commodity.getPrice();

        //获取 折扣价格
        Double discount = 1.0;
        Double totalDiscount = settingService.getDiscount();
        Double commodityDiscount = parseDiscount(commodity.getDiscount());
        discount = totalDiscount * commodityDiscount;
        //总价
        Double result = (price + multiplierMoney + levelMoney) * count * bluePicMoney * discount;
        orderFrom.setMoneyDouble(result);
        orderFrom.setDelete(Constants.State.DEFAULT_STATE);
    }

    private Double parseDiscount(String discount) {
        Double aDouble = MyUtil.NumberUtil.asDouble(discount);
        return parseDiscount(aDouble);
    }

    private Double parseDiscount(Double discount) {
        double result = 1.0;
        if (discount != null && discount > 0) {
            result = discount * 0.1;
        }
        return result;
    }

    /**
     * 直接购买
     *
     * @param orderFromDto 订单信息
     */
    @Override
    public R buy(OrderFromDto orderFromDto) {
        OrderFrom orderFrom = orderFromDto.toEntity();
        return buyOne(orderFrom);
    }

    /**
     * 重新发货
     *
     * @param id 订单ID
     */
    @Override
    public R reBuy(String id) {
        OrderFrom orderFrom = orderFromMapper.selectById(id);
        if (orderFrom == null) {
            throw new RuntimeException("找不到订单");
        }
        if (!Constants.Order.ERROR.equals(orderFrom.getState())) {
            throw new RuntimeException("只有发货失败的订单才可以重新发货");
        }
        return buyOne(orderFrom);
    }

    /**
     * 单买
     *
     * @param orderFrom 订单信息
     * @return 结果
     */
    private R buyOne(OrderFrom orderFrom) {
        try {
            Long buyUserId = orderFrom.getBuyUserId();
            UserInfo buyUserInfoFromDb = userInfoMapper.selectById(buyUserId);
            handleOrderFrom(orderFrom, buyUserInfoFromDb);
            orderFrom.setState(Constants.Order.SUCCESS);
            orderFrom.setErrorMsg("");
            orderFromMapper.updateById(orderFrom);
            userInfoMapper.updateById(buyUserInfoFromDb);
            return R.SUCCESS("发货成功", new OrderFromVo(orderFrom));
        } catch (Exception e) {
            String msg = "发货失败，原因：" + e.getMessage();
            orderFrom.setState(Constants.Order.ERROR);
            orderFrom.setErrorMsg(msg);
            orderFromMapper.updateById(orderFrom);
            return R.FAILED(msg);
        }
    }

    /**
     * 处理订单
     *
     * @param orderFrom         订单信息
     * @param buyUserInfoFromDb 付款用户信息
     */
    private void handleOrderFrom(OrderFrom orderFrom, UserInfo buyUserInfoFromDb) {
        orderFrom.setBuyUserId(buyUserInfoFromDb.getId());
        orderFrom.setState(Constants.Order.WAIT_GET);
        checkAndCalcMsg(orderFrom, true);
        UserBase userBaseToUser = null;
        Long toUserId = orderFrom.getToUserId();
        if (toUserId == null) {
            orderFrom.setToUserId(orderFrom.getBuyUserId());
        } else {
            userBaseToUser = userBaseMapper.selectById(toUserId);
            if (userBaseToUser == null) {
                throw new RuntimeException("找不到赠送用户");
            }
        }

        AddressMap address = orderFrom.getAddressMap();
        String sendType = address.getSendType();
        //检查收货方有没有绑定steamID
        String receiveId = "";
        String receiveTypeName = "";
        String[] receiveIdAndTypeName = new String[]{"", ""};
        if (userBaseToUser == null) {
            receiveIdAndTypeName = getReceiveId(buyUserInfoFromDb, sendType);
        } else {
            UserInfo toUserInfoFromDb = userInfoMapper.selectById(toUserId);
            receiveIdAndTypeName = getReceiveId(toUserInfoFromDb, sendType);
        }
        receiveId = receiveIdAndTypeName[0];
        receiveTypeName = receiveIdAndTypeName[1];
        if (MyUtil.StringUtil.isEmpty(receiveId)) {
            String msg = "";
            if (userBaseToUser == null) {
                msg = "您未绑定" + receiveTypeName + "，请到 个人中心->游戏绑定 界面绑定后重试。";
            } else {
                msg = "接收方未绑定" + receiveTypeName + "，请到 个人中心->游戏绑定 界面绑定后重试。接收方账户名：" + userBaseToUser.getName();
            }
            throw new RuntimeException(msg);
        }

        //检查余额是否够
        Double orderMoney = Double.parseDouble(orderFrom.getMoney());
        Double money = Double.parseDouble(buyUserInfoFromDb.getMoney());
        Double amount = Double.parseDouble(buyUserInfoFromDb.getAmount());
        if (Double.compare(money, orderMoney) < 0) {
            throw new RuntimeException("账户余额不足");
        }

        //发货
        String host = address.getIp();
        String ip = MyUtil.ServletUtil.getIPAddress(host);
        int port = address.getRconPort();
        String password = address.getPassword();
        Rcon rcon = new Rcon();
        try {
            rcon.connect(ip, port, password.getBytes());
        } catch (IOException e) {
            throw new RuntimeException("服务器连接失败：" + e.getMessage());
        }
        try {
            //发货特殊处理
            String payload = getPayload(orderFrom, receiveId);
            sendGoods(payload, rcon, orderFrom, buyUserInfoFromDb, ip, port, password.getBytes());
            money = money - orderMoney;
            amount = amount + orderMoney;
            buyUserInfoFromDb.setMoneyDouble(money);
            buyUserInfoFromDb.setAmountDouble(amount);
            userInfoMapper.updateById(buyUserInfoFromDb);
        } catch (Exception e) {
            userInfoMapper.updateById(buyUserInfoFromDb);
            throw e;
        }


    }

    /**
     * 获取发货人的ID,发货人ID类型 根据地图类型
     *
     * @param buyUserInfoFromDb 用户信息
     * @param sendType          发货类型
     * @return [发货人的ID, 发货人ID类型]
     */
    private static String[] getReceiveId(UserInfo buyUserInfoFromDb, String sendType) {
        String receiveId;
        String receiveName;
        String prefixName;
        String prefixName2;
        if (Constants.Map.SEND_TYPE_GAME_ID.equals(sendType)) {
            receiveId = buyUserInfoFromDb.getGameId();
            receiveName = "EosID";
            prefixName = "GiveItemToEOSId";
            prefixName2 = "SpawnDinoBP";
        } else {
            receiveId = buyUserInfoFromDb.getSteamId();
            receiveName = "SteamID";
            prefixName = "GiveItemToSteamId";
            prefixName2 = "SpawnDinoBP";
        }
        return new String[]{receiveId, receiveName, prefixName, prefixName2};
    }

    private void sendGoods(String payload, Rcon rcon, OrderFrom orderFrom, UserInfo buyUserInfoFromDb, String host, int port, byte[] password) {
        try {
            String lastMsg = "";
            Integer count = orderFrom.getCount();
            for (Integer i = 0; i < count; i++) {
                rcon.connect(host, port, password);
                String result = rcon.command(payload);
                orderFrom.setErrorMsg(result);
                if (!result.contains("Successfully")) {
                    //批量发货失败了，将订单拆分为2份，一份为成功，保存起来，一份为失败，报错抛出
                    if (i != 0) {
                        orderFrom.setCount(count - i);
                        OrderFrom orderFromOK = new OrderFrom();
                        orderFromOK.setCount(i);
                        orderFromOK.setErrorMsg(lastMsg);
                        orderFromOK.setDelete(orderFrom.getDelete());
                        orderFromOK.setBuyUserId(orderFrom.getBuyUserId());
                        orderFromOK.setLevel(orderFrom.getLevel());
                        orderFromOK.setToUserId(orderFrom.getToUserId());
                        orderFromOK.setErrorMsg(lastMsg);
                        orderFromOK.setAddressId(orderFrom.getAddressId());
                        orderFromOK.setName(orderFrom.getName());
                        orderFromOK.setState(Constants.Order.SUCCESS);
                        orderFromOK.setCommodityId(orderFrom.getCommodityId());
                        orderFromOK.setIsBluePic(orderFrom.getIsBluePic());
                        orderFromOK.setMultiplier(orderFrom.getMultiplier());

                        Double totalMoney = Double.parseDouble(orderFrom.getMoney());
                        Double moneyOk = totalMoney / count * i;
                        orderFrom.setMoneyDouble(totalMoney - moneyOk);
                        orderFromOK.setMoneyDouble(moneyOk);

                        Double money = Double.parseDouble(buyUserInfoFromDb.getMoney());
                        Double amount = Double.parseDouble(buyUserInfoFromDb.getAmount());
                        money = money - moneyOk;
                        amount = amount + moneyOk;
                        buyUserInfoFromDb.setMoneyDouble(money);
                        buyUserInfoFromDb.setAmountDouble(amount);
                        userInfoMapper.updateById(buyUserInfoFromDb);
                        orderFromMapper.insert(orderFromOK);
                    }
                    System.out.println(payload);
                    String tips = getResultTips(result);
                    System.out.println(result + tips);
                    throw new RuntimeException(result + tips);
                }
                lastMsg = result;
            }
            orderFrom.setErrorMsg(lastMsg);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    /**
     * 获取服务器返回消息的提示后缀
     *
     * @param result 服务器返回结果
     */
    private String getResultTips(String result) {
        String tips = "   ";
        if (result.contains("Can't find player from the given")) {
            //Can't find player from the given steam id
            //Can't find player from the given eos id
            tips = tips + "提醒：请确认 “玩家角色是否在线” 或者 “发货地图是否正确”";
        }
        return tips;
    }

    /**
     * 获取发货指令
     *
     * @param orderFrom 订单信息
     * @param receiveId 游戏用户码
     */
    private String getPayload(OrderFrom orderFrom, String receiveId) {
        Commodity commodity = orderFrom.getCommodity();
        CommodityCategory commodityCategory = orderFrom.getCommodityCategory();
//        String
        String codePrefix = commodityCategory.getCodePrefix();
        String code = commodity.getCode();
        Integer count = 1;
        Integer level = orderFrom.getLevel();
        Integer multiplier = orderFrom.getMultiplier();
        String isBluePic = orderFrom.getIsBluePic();
        //todo 命令格式
        // GiveItem 76561199002611511 "Blueprint'/Game/PrimalEarth/CoreBlueprints/Weapons/PrimalItem_WeaponRifle.PrimalItem_WeaponRifle'" 数量 质量 是否图纸  //物品
        // SpawnDino 76561199002611511 Blueprint'/Game/PrimalEarth/Dinos/Ankylo/Ankylo_Character_BP.Ankylo_Character_BP' 等级 是否野生 0 0 0      恐龙
        code = code.replaceAll("\"", "");
        String payload = "";
        switch (codePrefix) {
            case "GiveItem"://rcon 3.3 发物品
            case "GiveItemToSteamId"://rcon 3.4 发物品
            case "GiveItemToEOSId"://rcon 3.4 发物品
                count = getCountFromName(commodity.getName());
                payload = codePrefix + " " + receiveId + " " + code + " ";
                payload += count + " " + multiplier + " " + isBluePic;
                break;
            case "SpawnDino"://rcon 3.3 发龙 SpawnDino SteamID或EOSID 恐龙路径 恐龙等级 是否驯服 是否绝育
                payload = codePrefix + " " + receiveId + " " + code + " ";
                payload += level + " " + "1 0 0 0";
                break;
            case "SpawnDinoBP"://rcon 3.4 发龙 SpawnDinoBP  SteamID或EOSID 恐龙路径 恐龙等级 是否驯服 是否绝育 距离玩家X 距离玩家Y 距离玩家Z
                payload = codePrefix + " " + receiveId + " " + code + " ";
                payload += level + " " + "1 0 0 0 0";
                break;
            case "Customize"://自定义
                payload = code.replace("#playerId", receiveId) + " ";
                break;
            default:
                throw new RuntimeException("找不到指令前缀");
        }
        return payload;
    }

    /**
     * 从商品名称获取数量
     *
     * @param name 商品 名称
     * @return 数量
     */
    private static Integer getCountFromName(String name) {
        //判断有无大中小括号
        int count = 1;
        if (name.matches(".*[\\(\\)\\[\\]\\{\\}].*")) {
            // 创建正则表达式，提取大中小括号中的数字
            // 创建模式匹配器
            Pattern pattern = Pattern.compile("[\\(\\[\\{](\\d+)[\\)\\]\\}]");
            Matcher matcher = pattern.matcher(name);
            matcher.find();
            count = Integer.parseInt(matcher.group(1));
        }
        return count;
    }

    /**
     * 购物车购买
     *
     * @param orderFromList 订单ID列表
     */
    @Override
    public R buyList(List<OrderFromDto> orderFromList) {
        Map<Long, List<OrderFrom>> orderFromMap = orderFromList.stream().map(OrderFromDto::toEntity).collect(Collectors.groupingBy(OrderFrom::getId));
        List<OrderFrom> orderFroms = orderFromMapper.selectBatchIds(orderFromMap.keySet());
        if (orderFroms == null || orderFroms.isEmpty()) {
            throw new RuntimeException("找不到订单");
        }
        Long buyUserId = orderFroms.get(0).getBuyUserId();
        UserInfo buyUserInfoFromDb = userInfoMapper.selectById(buyUserId);

        String errorMsg = null;
        for (OrderFrom orderFrom : orderFroms) {
            try {
                //填充信息
                List<OrderFrom> orderFromWebList = orderFromMap.get(orderFrom.getId());
                if (orderFromWebList == null || orderFromWebList.isEmpty()) {
                    continue;
                }
                OrderFrom orderFromWeb = orderFromWebList.get(0);
                orderFrom.setAddressId(orderFromWeb.getAddressId());
                orderFrom.setToUserId(orderFromWeb.getToUserId());
                //发货
                handleOrderFrom(orderFrom, buyUserInfoFromDb);
                //收尾
                orderFrom.setState(Constants.Order.SUCCESS);
                orderFromMapper.updateById(orderFrom);
            } catch (Exception e) {
                e.printStackTrace();
                errorMsg = "发货失败，原因：" + e.getMessage();
                orderFrom.setState(Constants.Order.ERROR);
                orderFrom.setErrorMsg(errorMsg);
                orderFromMapper.updateById(orderFrom);
            }
        }
        if (errorMsg == null) {
            return R.SUCCESS("发货成功");
        } else {
            return R.FAILED(errorMsg);
        }
    }

    /**
     * 获取订单列表
     *
     * @param orderFromSearchDto 搜索条件
     */
    @Override
    public R getListAdmin(OrderFromSearchDto orderFromSearchDto) {
        Page<OrderFrom> pageMp = orderFromSearchDto.getPageMp();
        String keyword = orderFromSearchDto.getKeyword();
        String state = orderFromSearchDto.getState();
        Date startTime = orderFromSearchDto.getStartTime();
        Date endTime = orderFromSearchDto.getEndTime();
        Long userId = orderFromSearchDto.getUserId();
        Long projectId = orderFromSearchDto.getProjectId();
        Long categoryId = orderFromSearchDto.getCategoryId();
        Page<OrderFrom> pageResult = null;
        if (permissionService.ROOT()) {
            pageResult = orderFromMapper.findList(keyword, state, userId, projectId, categoryId, startTime, endTime, null, pageMp);
        } else {
            pageResult = orderFromMapper.findList(keyword, state, userId, projectId, categoryId, startTime, endTime, Constants.State.DEFAULT_STATE, pageMp);
        }
        PageMp<OrderFromVo> orderFromVoPageMp = new PageMp<>(pageResult, OrderFromVo::new);
        return R.SUCCESS("列表获取成功").setData(orderFromVoPageMp);
    }

    /**
     * 获取订单列表
     *
     * @param orderFromSearchDto 搜索条件
     */
    @Override
    public R getListPortal(OrderFromSearchDto orderFromSearchDto) {
        UserVo userVo = LoginUserThreadLocalUtil.get();
        if (userVo == null) {
            return R.SUCCESS("列表获取成功").setData(new PageMp<>());
        }
        Page<OrderFrom> pageMp = orderFromSearchDto.getPageMp();
        Long userId = MyUtil.NumberUtil.asLong(userVo.getId());
        String keyword = orderFromSearchDto.getKeyword();
        String state = orderFromSearchDto.getState();
        Date startTime = orderFromSearchDto.getStartTime();
        Date endTime = orderFromSearchDto.getEndTime();
        Long projectId = orderFromSearchDto.getProjectId();
        Long categoryId = orderFromSearchDto.getCategoryId();
        Page<OrderFrom> pageResult = orderFromMapper.findList(keyword, state, userId, projectId, categoryId, startTime, endTime, Constants.State.DEFAULT_STATE, pageMp);
        PageMp<OrderFromVo> orderFromVoPageMp = new PageMp<>(pageResult, OrderFromVo::new);
        return R.SUCCESS("列表获取成功").setData(orderFromVoPageMp);
    }

    /**
     * 删除订单信息
     *
     * @param ids ids列表
     */
    @Override
    public R delPortal(List<String> ids) {
        if (ids != null && !ids.isEmpty()) {
            List<Long> list = ids.stream().map(Long::parseLong).toList();
            List<OrderFrom> orderFroms = orderFromMapper.selectBatchIds(list);
            Set<Long> del = new HashSet<>();
            Set<OrderFrom> update = new HashSet<>();
            boolean root = permissionService.ROOT();
            for (OrderFrom orderFrom : orderFroms) {
                if (Constants.Order.SAVE.equals(orderFrom.getState())) {
                    del.add(orderFrom.getId());
                } else {
                    if (Constants.State.DELETE_STATE.equals(orderFrom.getDelete()) && root) {
                        del.add(orderFrom.getId());
                    } else {
                        orderFrom.setDelete(Constants.State.DELETE_STATE);
                        update.add(orderFrom);
                    }
                }
            }
            if (!del.isEmpty()) {
                orderFromMapper.deleteBatchIds(del);
            }
            for (OrderFrom orderFrom : update) {
                orderFromMapper.updateById(orderFrom);
            }
        }
        return R.SUCCESS("删除成功");
    }


    /**
     * @param giftChar      礼物列表
     * @param addressIdLong 地址ID
     * @param userInfoDb    用户信息
     */
    @Override
    public void sendNewGift(List<String> giftChar, Long addressIdLong, UserInfo userInfoDb) {
        AddressMap addressMap = addressMapper.selectById(addressIdLong);
        if (addressMap == null) {
            throw new RuntimeException("找不到地图信息");
        }
        try {
            String sendType = addressMap.getSendType();
            String[] receiveIdAndName = getReceiveId(userInfoDb, sendType);
            String receiveId = receiveIdAndName[0];
            String giveItemName = receiveIdAndName[2];
            String spawnDinoName = receiveIdAndName[3];

            List<String> giftPayload = new ArrayList<>();
            for (String gift : giftChar) {
                gift = gift.replace("#playerId", receiveId) + " ";
                gift = gift.replace("GiveItem", giveItemName);
                gift = gift.replace("SpawnDino", spawnDinoName);
                giftPayload.add(gift);
            }
            String host = addressMap.getIp();
            String ip = MyUtil.ServletUtil.getIPAddress(host);
            int port = addressMap.getRconPort();
            String password = addressMap.getPassword();
            Rcon rcon = null;
            boolean isSuccess = false;
            for (String payload : giftPayload) {
                rcon = new Rcon();
                rcon.connect(ip, port, password.getBytes());
                String result = rcon.command(payload);
                if (!result.contains("Successfully")) {
                    if (isSuccess) {
                        log.error("发货发生异常，代码：{}    错误信息：{}", payload, result);
                    } else {
                        String tips = getResultTips(result);
                        throw new RuntimeException("发货发生异常，错误信息：" + result + " , 提示：" + tips);
                    }
                }
                isSuccess = true;
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("发货发生异常，错误信息：" + e.getMessage(), e);
        }
    }

    /**
     * 删除订单信息（物理删除）
     *
     * @param ids ids列表
     */
    @Override
    public R delAdmin(List<String> ids) {
        orderFromMapper.deleteBatchIds(ids);
        return R.SUCCESS("删除成功");
    }
}
